<?php
namespace Tbf\Bundle\YntAuthBundle\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Tbf\Bundle\YntAuthBundle\MediaImpInterface;
use Tbf\Bundle\YntAuthBundle\Model\Media;

class MediaManager {
    /**
     * @var array map[name_en]Media
     */
    protected $name_en_map = array();
    /**
     * @var array map[name_en]name_en
     */
    protected $name_en_alias = array();
    /**
     * @var array map[name_en]MediaImpInterface|
     */
    protected $name_en_imp_map = array();
    /**
     * 1.加快加载速度,
     * 2.防止出现dic依赖循环
     * @var array map[name_en]service_id
     */
    protected $lazy_name_en_imp_service_id_map = array();
    /**
     * @var ContainerInterface
     */
    protected $container;
    function __construct(ContainerInterface $container=null,
                         $lazy_name_en_imp_service_id_map=array(),
                         $name_en_alias = array()
                ){
        $this->container = $container;
        $this->lazy_name_en_imp_service_id_map = $lazy_name_en_imp_service_id_map;
        $this->name_en_alias = $name_en_alias;
    }
    /**
     * @param Media $media
     * @return MediaManager
     */
    function registerMedia(Media $media){
        $this->name_en_map[$media->getNameEn()] = $media;
        $media->setMediaManager($this);
        return $this;
    }
    /**
     * @param string $name_en
     * @param MediaImpInterface $imp
     * @return MediaManager
     */
    function setMediaImpByMediaEn($name_en,MediaImpInterface $imp){
        $this->name_en_imp_map[$name_en] = $imp;
        return $this;
    }

    /**
     * @param $name_en
     * @return MediaImpInterface
     */
    function getMediaImpByMediaNameEn($name_en){
        if (!empty($this->name_en_alias[$name_en])){
            $name_en = $this->name_en_alias[$name_en];
        }
        if (!empty($this->name_en_imp_map[$name_en])){
            return $this->name_en_imp_map[$name_en];
        }
        if (!empty($this->lazy_name_en_imp_service_id_map[$name_en])){
            $this->name_en_imp_map[$name_en] = $this->container->get($this->lazy_name_en_imp_service_id_map[$name_en]);
            return $this->name_en_imp_map[$name_en];
        }
        return null;
    }

    /**
     * @param $name_en
     * @return Media
     */
    function getMediaByMediaNameEn($name_en){
        if (!empty($this->name_en_alias[$name_en])){
            $name_en = $this->name_en_alias[$name_en];
        }
        return $this->name_en_map[$name_en];
    }
}